package com.studytime;

import java.util.Arrays;
import java.util.Collection;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.FacebookRequestError;
import com.facebook.HttpMethod;
import com.facebook.Request;
import com.facebook.RequestAsyncTask;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;

public class StudyActivity extends Activity {
	private ImageButton startButton;
	private ImageButton pauseButton;
	private ImageButton stopButton;
	private ImageButton shareButton;
	private ImageButton shareButtonGrey;

	private TextView timerValue;

	private long startTime = 0L;

	private String timeTotal;

	private Handler customHandler = new Handler();

	long timeInMilliseconds = 0L;
	long timeSwapBuff = 0L;
	long updatedTime = 0L;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.study);

		timerValue = (TextView) findViewById(R.id.timer);

		startButton = (ImageButton) findViewById(R.id.startBtn);

		startButton.setOnClickListener(new View.OnClickListener() {

			public void onClick(View view) {
				startTime = SystemClock.uptimeMillis();
				customHandler.postDelayed(updateTimerThread, 0);

			}
		});

		pauseButton = (ImageButton) findViewById(R.id.pauseBtn);

		pauseButton.setOnClickListener(new View.OnClickListener() {

			public void onClick(View view) {

				timeSwapBuff += timeInMilliseconds;
				customHandler.removeCallbacks(updateTimerThread);

			}
		});
		stopButton = (ImageButton) findViewById(R.id.stopBtn);

		stopButton.setOnClickListener(new View.OnClickListener() {

			public void onClick(View view) {
				timeTotal = timerValue.getText().toString();
				// Toast.makeText(StudyActivity.this, "time="+timeTotal,
				// Toast.LENGTH_SHORT).show();
				timerValue.setText("00:00:00");
				timeInMilliseconds = 0L;
				timeSwapBuff = 0L;
				updatedTime = 0L;
				shareButtonGrey.setVisibility(View.INVISIBLE);
				shareButton.setVisibility(View.VISIBLE);

			}
		});

		shareButtonGrey = (ImageButton) findViewById(R.id.shareBtnGrey);
		shareButton = (ImageButton) findViewById(R.id.shareBtn);
		shareButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				// share to facebook
				publishStory();
			}
		});
	}

	private Runnable updateTimerThread = new Runnable() {

		public void run() {

			timeInMilliseconds = SystemClock.uptimeMillis() - startTime;

			updatedTime = timeSwapBuff + timeInMilliseconds;

			int secs = (int) (updatedTime / 1000);
			int mins = secs / 60;
			secs = secs % 60;
			int milliseconds = (int) (updatedTime % 1000);
			timerValue.setText("" + mins + ":" + String.format("%02d", secs)
					+ ":" + String.format("%03d", milliseconds));
			customHandler.postDelayed(this, 0);
		}

	};
	//Share on FB
	private static final List<String> PERMISSIONS = Arrays
			.asList("publish_actions");
	private static final String PENDING_PUBLISH_KEY = "pendingPublishReauthorization";
	private boolean pendingPublishReauthorization = false;

	private void publishStory() {
		Session session = Session.getActiveSession();

		if (session != null) {

			Bundle postParams = new Bundle();
			//Message that will be post on user's status
			postParams.putString("message", "Wow !! completed lesson in "
					+ timeTotal + " hr");
			
			Request.Callback callback = new Request.Callback() {
				public void onCompleted(Response response) {
					JSONObject graphResponse = response.getGraphObject()
							.getInnerJSONObject();
					String postId = null;
					try {
						postId = graphResponse.getString("id");
					} catch (JSONException e) {
						System.out.println("JSON error " + e.getMessage());
					}
					FacebookRequestError error = response.getError();
					if (error != null) {
						Toast.makeText(StudyActivity.this,
								error.getErrorMessage(), Toast.LENGTH_SHORT)
								.show();
					} else {
						Toast.makeText(StudyActivity.this, "Published",
								Toast.LENGTH_LONG).show();
					}
				}
			};

			Request request = new Request(session, "me/feed", postParams,
					HttpMethod.POST, callback);

			RequestAsyncTask task = new RequestAsyncTask(request);
			task.execute();
		}

	}

	private boolean isSubsetOf(Collection<String> subset,
			Collection<String> superset) {
		for (String string : subset) {
			if (!superset.contains(string)) {
				return false;
			}
		}
		return true;
	}

	private void onSessionStateChange(Session session, SessionState state,
			Exception exception) {
		if (state.isOpened()) {
			if (pendingPublishReauthorization
					&& state.equals(SessionState.OPENED_TOKEN_UPDATED)) {
				pendingPublishReauthorization = false;
				publishStory();
			}
		} else if (state.isClosed()) {
			shareButton.setVisibility(View.INVISIBLE);
		}
	}
}
